package com.zhp.controller.article;

import com.zhp.common.Constant;
import com.zhp.controller.BaseController;
import com.zhp.model.Article;
import com.zhp.model.Favorite;
import com.zhp.model.User;
import com.zhp.service.ArticleService;
import com.zhp.service.FavoriteService;
import com.zhp.service.impl.ArticleServiceImpl;
import com.zhp.service.impl.FavoriteServiceImpl;
import com.zhp.utils.PageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

@WebServlet("/article/*")
public class ArticleController extends BaseController {
    private ArticleService articleService = new ArticleServiceImpl();
    private FavoriteService favoriteService = new FavoriteServiceImpl();

    public void getArticles(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String page = req.getParameter("page");
            String name = req.getParameter("searchName");
            int currentPage = 1;
            if (null != page) {
                currentPage = Integer.parseInt(page);
            }
//          从会话拿到当前用户得Id
            Map userinfo = (Map) req.getSession().getAttribute("userinfomap");
            String userId = userinfo.get("userId").toString();
            List<Map<String, Object>> articles = articleService.getArticles(userId, currentPage, name);
            req.setAttribute("articles", articles);
            long totalCount = articleService.getArticleCount(name);
            long totalPage = PageUtil.getTotalPage(totalCount);
            long startPage = PageUtil.getStratPage(currentPage);
            long endPage = PageUtil.getEndPage(currentPage, totalCount);
            req.setAttribute("currentPage", currentPage);
            req.setAttribute("searchName", name);
            req.setAttribute("totalCount", totalCount);
            req.setAttribute("totalPage", totalPage);
            req.setAttribute("pageCount", Constant.PAGE_COUNT);
            req.setAttribute("startPage", startPage);
            req.setAttribute("endPage", endPage);
            req.getRequestDispatcher("/assets/html/article.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getAriticleInfo(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String id = req.getParameter("id");  //文章ID
            String iffavorite = req.getParameter("iffavorite");  //判断这文章是否被收藏 1为收藏了  0未收藏
            Article article = articleService.findByid(id);  //文章详情
            article.setBrowseCount(article.getBrowseCount() + 1);  // 浏览次数+1
            articleService.update(article); //更新浏览次数
            Number num = articleService.getfavorite(id);  //被收藏数
            List<User> userFavorite = articleService.getUserFavorite(id); //关注的人中，收藏了这个文章的人，
            req.setAttribute("userFavorite", userFavorite);
            req.setAttribute("article", article);
            req.setAttribute("num", num);
            req.setAttribute("iffavorite", iffavorite);
            req.getRequestDispatcher("/assets/html/article_detail.jsp").forward(req, resp);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }

    }

    public void articlesAdd(HttpServletRequest req, HttpServletResponse resp) {
        try {
            Map<String, Object> userinfomap = (Map<String, Object>) req.getSession().getAttribute("userinfomap");
            String userId = getUserId(req);
            String title = req.getParameter("title");
            String content = req.getParameter("content");
            Article article = new Article();
            article.setTitle(title);
            article.setContent(content);
            article.setBrowseCount(0);
            article.setPublishDate(new Date());
            article.setPublishUsername((String) userinfomap.get("username"));
            article.setUserId(Integer.valueOf(userId));
            int i = articleService.addArticle(article);
            if (i > 0) {
                req.getRequestDispatcher("/article/getArticles").forward(req, resp);
            }
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }

    public void delfa(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String uId = getUserId(req);
            String aId = req.getParameter("a_id");
            int row = articleService.delFavorite(uId, aId);
            if (row > 0) {
                req.getRequestDispatcher("/article/getAriticleInfo?id=" + aId + "&iffavorite=0").forward(req, resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addfa(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String uId = getUserId(req);
            String aId = req.getParameter("a_id");
            Favorite favorite = new Favorite();
            favorite.setAId(Integer.valueOf(aId));
            favorite.setUId(Integer.valueOf(uId));
            int row = articleService.addFavorite(favorite);
            if (row > 0) {
                req.getRequestDispatcher("/article/getAriticleInfo?id=" + aId + "&iffavorite=1").forward(req, resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void myFavorite(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String page = req.getParameter("page");
            String name = req.getParameter("searchName");
            int currentPage = 1;
            if (null != page) {
                currentPage = Integer.parseInt(page);
            }
//          从会话拿到当前用户得Id
            Map userinfo = (Map) req.getSession().getAttribute("userinfomap");
            String userId = userinfo.get("userId").toString();
            List<Map<String, Object>> articles = articleService.getMyArticles(userId, currentPage, name);
            req.setAttribute("articles", articles);
            long totalCount = articleService.getMyArticleCount(userId, name);
            long totalPage = PageUtil.getTotalPage(totalCount);
            long startPage = PageUtil.getStratPage(currentPage);
            long endPage = PageUtil.getEndPage(currentPage, totalCount);
            req.setAttribute("currentPage", currentPage);
            req.setAttribute("searchName", name);
            req.setAttribute("totalCount", totalCount);
            req.setAttribute("totalPage", totalPage);
            req.setAttribute("pageCount", Constant.PAGE_COUNT);
            req.setAttribute("startPage", startPage);
            req.setAttribute("endPage", endPage);
            req.getRequestDispatcher("/assets/html/article_collect.jsp").forward(req, resp);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
